package com.andreiamariei.tema6.servlets;

import java.io.IOException;
import java.sql.Connection;
import java.sql.DriverManager;
import java.util.HashMap;

import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import net.sf.jasperreports.engine.JasperCompileManager;
import net.sf.jasperreports.engine.JasperReport;
import net.sf.jasperreports.engine.JasperRunManager;
import net.sf.jasperreports.engine.design.JasperDesign;
import net.sf.jasperreports.engine.xml.JRXmlLoader;

public class ReportingServlet extends HttpServlet {

	@Override
	protected void doGet(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {

		try {

			String path = req.getServletContext().getRealPath("\\reports\\Raport.jrxml");
			
			JasperDesign jasperDesign = JRXmlLoader.load(path);
			JasperReport jasperReport = JasperCompileManager
					.compileReport(jasperDesign);
			Class.forName("com.mysql.jdbc.Driver");
			Connection jdbcConnection = DriverManager.getConnection(
					"jdbc:mysql://localhost/tema6", "root", "root");
			byte[] bytes = JasperRunManager.runReportToPdf(jasperReport, new HashMap<Object, Object>(), jdbcConnection);
			resp.setContentType("application/pdf");
			resp.setContentLength(bytes.length);

		    ServletOutputStream outStream = resp.getOutputStream();
		    outStream.write(bytes, 0, bytes.length);
		    outStream.flush();
		    outStream.close();
			
		} catch (Exception ex) {
			String connectMsg = "Could not create the report "
					+ ex.getMessage() + " " + ex.getLocalizedMessage();
			System.out.println(connectMsg);
		}

		

	}

}
